<template>
	<view class="page add-address">
		<fu-custom :isBack="true" :isBottom="true">
			<block slot="content">{{edit_id?i18n['编辑']:i18n['添加地址']}}</block>
			<block slot="right"><text v-if="edit_id" @click="delAddr" class="text-lg text-333">{{i18n['删除']}}</text>
			</block>
		</fu-custom>
		<!-- 表单信息 start -->
		<view class="addAddr">
			<view class="cell" v-if="serveList.length > 0">
				<text class="title">{{i18n['标签']}}</text>
				<view class="flex align-center">
					<view v-for='(item,index) in serveList' :key='index' class='cu-tag radius'
						:class='item.name == default_serve.name? index < 3? "bg-theme text-white":"bg-theme text-white radius-left" :"line-black"'
						@click='changeServe(item)' v-show="item.name">
						{{item.name}}
					</view>
					<view v-if="serveList.length== 4" class='cu-tag radius bg-theme text-white left-0 radius-right'
						@click='addServe(serveList[3].name)'>
						{{i18n["编辑"]}}
					</view>
					<view class='cu-tag line-black radius' @click='addServe()' v-if="serveList.length<= 3">+</view>
				</view>
			</view>
			<view class="cell">
				<text class="title">{{i18n["收货人"]}}</text>
				<input type="text" maxlength="10" v-model="name" :placeholder="i18n['收货人']" />
				<view class="flex">
					<view class="text-999 flex align-center" @click="chooseSex('1')">
						<text :class="[sex == 1 ? 'cuIcon-roundcheckfill active' : 'cuIcon-round']"
							class="text-xl"></text>
						<text :class="{'text-666': sex == 1}" class="margin-left-xs">{{i18n["先生"]}}</text>
					</view>
					<view class="text-999 margin-left  flex align-center" @click="chooseSex('2')">
						<text :class="[sex == 2 ? 'cuIcon-roundcheckfill active' : 'cuIcon-round']"
							class="text-xl"></text>
						<text :class="{'text-666': sex == 2}" class="margin-left-xs">{{i18n['女士']}}</text>
					</view>
				</view>
			</view>
			<view class="cell">
				<text class="title"> {{i18n["联系电话"]}}</text>
				<input type="number" maxlength="11" v-model="phone" :placeholder="i18n['联系电话']" />
				<!-- <text v-if="phone.length > 0" class=" cuIcon-close" @click="clear"
					style="font-size: 36rpx;color:#999;"></text> -->
			</view>
			<view class="cell">
				<text class="title"> {{i18n["所在地区"]}}</text>
				<view class="flex flex-sub">
					<input class="flex-sub" type="text" disabled v-model="address" :placeholder="i18n['请选择省市区县、乡镇']"
						@click="showMulLinkageThreePicker" />
					<!-- 	<text class="margin-right cuIcon-locationfill text-gray" style="font-size: 40rpx; "
						@click="location"></text> -->
					<!-- <text class=" cuIcon-right text-gray" style="font-size: 36rpx; "
						@click="showMulLinkageThreePicker"></text> -->
				</view>
			</view>
			<view class="cell">
				<textarea class="text-area" type="text" v-model="addressDesc" maxlength="50"
					placeholder-class="placeholder" :placeholder="i18n['请输入详细地址：如道路、门牌号、小区、楼栋号等']" />
			</view>
			<view class="flex justify-between cell">
				<view class="">{{i18n['设置默认地址']}}</view>
				<switch class="switch" :color="is_default?addRadioColor:addRadioDefaultColor" @change="handleSwitch"
					:checked="is_default ? true : false"></switch>
			</view>
		</view>
		<!-- 表单信息 end -->
		<!-- 服务标签弹框 start -->
		<view class="" v-if="serve_show">
			<view class="serve-mask" @click="serve_show = false"></view>
			<view class="serve-pop flex align-center justify-center" :style="{bottom:keyboardheight+'px'}">
				<input type="text" :placeholder="i18n['请填写标签名称（最多5个字）']" v-model='serveKeyword' maxlength="5" focus
					:adjust-position='false' placeholder-class="placeholderServe">
				<button @click='addServeInfo()'>{{i18n['添加']}}</button>
			</view>
		</view>

		<!-- 服务标签弹框 end -->
		<!-- 底部占位 start -->
		<view class="bottom-status"></view>
		<!-- 底部占位 end -->
		<!-- 提交按钮 start -->
		<view class="bottom-action">
			<view class="btn2" @click="sub_sure">{{i18n['保存']}}</view>
		</view>
		<!-- 提交按钮 end -->
		<!-- 地址选择插件 start -->
		<w-picker mode="region" :value="defVal" default-type="label" :themeColor="themeColor"
			@confirm="onConfirm($event)" ref="region">{{i18n['选择所在地区']}}</w-picker>
		<!-- 地址选择插件 end -->
		<!-- 断网监测 start -->
		<fu-notwork></fu-notwork>
		<!-- 断网监测 end -->
	</view>
</template>

<script>
	import wPicker from '../components/w-picker/w-picker.vue'
	// 高德地图sdk
	import amapFile from '@/libs/amap-wx.js';
	export default {
		computed: {
			// 合并省市区信息字段
			address() {
				return this.province + this.city + this.district;
			},
			themeColor() {
				return this.$store.state.themeColor;
			}
		},
		components: {
			wPicker
		},
		data() {
			return {
				isagain: false,
				keyboardheight: 0, // 键盘高度
				serveKeyword: '', // 服务标签关键字
				serve_show: false, // 服务标签弹框
				serveList: [], // 服务标签
				default_serve: '', // 默认服务标签
				phone: '', // 联系电话
				name: '', // 收货人姓名
				sex: 1, // 性别 1:男 2:女
				is_default: true, // 是否设为默认地址
				edit_id: null, // 是否是修改收货地址
				myAmapFun: null, // 高德地图实例
				province: '', // 省
				city: '', //市
				district: '', //区
				provinceCode: '', // 省 code码
				cityCode: '', //市 code码
				districtCode: '', //区 code码
				addressDesc: '', // 详细地址
				customStyle: {
					'backgroundColor': '#cccccc',
					'color': '#ffffff',
				}, // 自定义按钮样式
				defVal: [],
				addRadioColor: '#28ca43',
				addRadioDefaultColor: '#bfbfbf'
			};
		},
		/**
		 * @description 页面入参
		 * @param {object} options = [id]
		 * @param {string} id = 修改的地址ID
		 */
		onLoad(options) {
			this.setNavigationBarTitle(this.i18n['添加地址'])
			// 监听键盘高度
			uni.onKeyboardHeightChange((res) => {
				console.log("键盘监听", res);
				this.keyboardheight = res.height;
			});
			// 初始化高德地图SDK,记得换成自己的key
			this.myAmapFun = new amapFile.AMapWX({
				key: '71e2d1e8fad67225279e724ff7c51e64'
			});
			//如果是修改地址
			if (options.id) {
				this.edit_id = options.id;
				// 换标题文字
				uni.setNavigationBarTitle({
					title: this.i18n['编辑']
				});
				// 获取要修改的地址信息
				this.get_editAddress();
			} else {
				// 自动定位当前地址
				// this.autoGetLocation();
				// 获取默认标签
				this.getLabelData()
			}
		},
		methods: {
			/**
			 * @description 删除地址
			 * */
			delAddr() {
				this.$util.showModal({
					title: this.i18n['提示'],
					content: this.i18n['确定删除该地址'] + '?',
					confirmColor: this.$store.state.themeColor,
					success: (res) => {
						if (res.confirm) {
							this.$api.post(global.apiUrls.postUserAddressDelAddress, {
									address_ids: this.edit_id
								})
								.then(res => {
									console.log(res);
									if (res.data.code == 1) {
										uni.navigateBack();
									} else {
										this.$message.info(res.msg);
									}
								});
						}
					}

				})
			},
			/**
			 * @func 获取服务标签列表
			 */
			getLabelData(val) {
				this.$api.post(global.apiUrls.getLabel, {}).then(res => {
					if (res.data.code == 1) {
						this.serveList = res.data.data
						let serve = uni.getStorageSync('DEFAULT_SERVE');
						// 加上编辑的标签
						if (serve && this.serveList != 0) {
							this.default_serve = this.serveList[0]
							this.serveList.push(JSON.parse(serve))
						}
						// 判断是否为编辑
						if (this.edit_id) {
							this.default_serve = {
								id: 0,
								name: val
							}
							var flag = this.serveList.filter((item) => {
								return item.name == val
							})
							if (flag.length == 0) {
								if(this.default_serve.name) this.serveList.push(this.default_serve);
							}
						} else {
							// if (serve &&  this.serveList !=0) {
							// 	this.default_serve = this.serveList[0]
							// 	this.serveList.push(JSON.parse(serve))
							// }
						}
					} else {
						this.$message.info(res.data.msg);
					}
				}).catch(err => {
					this.$message.info(err.msg);
				})
			},
			/**
			 * @description  自定义服务标签弹窗显示
			 * @param {String} name 回显自定义标签关键词
			 */
			addServe(name) {
				if (name) {
					this.serveKeyword = name
				}
				this.serve_show = true //弹窗显示
			},
			/**
			 * @func 新增服务标签
			 */
			addServeInfo() {
				let val = this.serveKeyword.trim()
				if (val) {
					var flag = this.serveList.filter((item) => {
						return item.name == val
					})
					if (flag.length == 0) {
						this.serve_show = false // 弹窗隐藏
						let serve = {
							id: 0,
							name: val
						}
						// 存在自定义标签
						if (this.serveList.length > 3) {
							this.serveList[3] = serve
						} else {
							this.serveList.push(serve)
						}
						this.default_serve = serve
						uni.setStorageSync('DEFAULT_SERVE', JSON.stringify(serve));
					} else {
						this.$message.info(this.i18n['标签已存在']);
					}
				} else {
					this.$message.info(this.i18n['请输入内容']);
				}
			},
			/**
			 * @description 切换服务标签
			 * @param {String} item = 服务标签关键字
			 */
			changeServe(item) {
				this.default_serve = item;
			},
			/**
			 * @description 选择性别
			 * @param {String} type = 性别
			 */
			chooseSex(type) {
				this.sex = type;
			},
			/**
			 * @func 获取修改地址信息
			 */
			get_editAddress() {
				this.$api.post(global.apiUrls.postUserAddressGetOneAddress, {
					address_id: this.edit_id
				}).then(res => {
					if (res.data.code == 1) {
						let data = res.data.data;
						this.name = data.name; // 收货人姓名
						this.phone = data.mobile; // 收货人电话
						this.province = data.province; // 省
						this.city = data.city; // 市
						this.district = data.district; // 区
						this.addressDesc = data.address; // 详细地址
						this.sex = data.sex; // 性别
						this.is_default = data.is_default == '1' ? true : false; // 是否默认
						this.defVal = [data.province, data.city, data.district];
						// 服务标签
						this.getLabelData(data.label_name)

					} else {
						this.$message.info(res.data.msg);
					}
				}).catch(err => {
					this.$message.info(err.msg);
				})
			},
			/**
			 * @func 显示地址选择弹窗
			 */
			showMulLinkageThreePicker() {
				uni.hideKeyboard();
				this.$refs.region.show();
			},
			/**
			 * @description 地址选择回调
			 * @param {Object} val = 地址信息对象
			 */
			onConfirm(val) {
				this.province = val.obj.province.label;
				this.city = val.obj.city.label;
				this.district = val.obj.area.label;
				this.provinceCode = val.value[0];
				this.cityCode = val.value[1];
				this.districtCode = val.value[2];
			},
			/**
			 * @func 切换是否为默认地址
			 */
			handleSwitch(e) {
				this.is_default = e.detail.value;
			},
			/**
			 * @func 定位地址
			 */
			location() {
				let _this = this;
				//#ifdef MP-WEIXIN
				uni.getSetting({
					success(res) {
						// 获取设置成功
						console.log(res.authSetting);
						if (!res.authSetting['scope.userLocation']) {
							// 如果没开启权限提示打开
							uni.openSetting({
								success(res) {
									// 打开成功，提示获取权限
									console.log(res.authSetting);
									uni.authorize({
										scope: 'scope.userLocation',
										success(res) {
											_this.chooseLocation();
										},
										fail(res) {
											console.log(res);
											this.$message.info(this.i18n['打开权限失败']);
										}
									});
								}
							});
						} else {
							_this.chooseLocation();
						}
					}
				});
				//#endif
				//#ifndef MP-WEIXIN
				this.chooseLocation();
				//#endif
			},
			/**
			 * @func 地图选点
			 */
			chooseLocation() {
				uni.chooseLocation({
					success: (res) => {
						console.log(res, '地图');
						this.myAmapFun.getRegeo({
							location: res.longitude + ',' + res.latitude,
							success: (data) => {
								//成功回调
								console.log('sdk回调', data);
								let regeoData = data[0].regeocodeData.addressComponent;
								this.province = regeoData.province;
								this.city = Array.isArray(regeoData.city) && (regeoData.city
									.length == 0) ? regeoData.province : regeoData.city;
								this.district = regeoData.district;
								this.addressDesc = res.address + res.name;
								this.provinceCode = regeoData.adcode.substr(0, 2) + '0000';
								this.cityCode = regeoData.adcode.substr(0, 4) + '00';
								this.districtCode = regeoData.adcode + '';
							},
							fail: (info) => {
								//失败回调
								console.log(info)
							}
						})
					}
				})
			},
			/**
			 * @func 自动定位
			 */
			autoGetLocation() {
				console.log("自动定位");
				uni.getLocation({
					geocode: true,
					success: (adr) => {
						this.myAmapFun.getRegeo({
							location: adr.longitude + ',' + adr.latitude,
							success: (data) => {
								//成功回调
								console.log('自动定位 SDK回调', data);
								let regeoData = data[0].regeocodeData.addressComponent;
								this.province = regeoData.province;
								this.city = Array.isArray(regeoData.city) && (regeoData.city
									.length == 0) ? regeoData.province : regeoData.city;
								this.district = regeoData.district;
								this.addressDesc = data[0].desc;
								this.provinceCode = regeoData.adcode.substr(0, 2) + '0000';
								this.cityCode = regeoData.adcode.substr(0, 4) + '00';
								this.districtCode = regeoData.adcode + '';
							},
							fail: (info) => {
								//失败回调
								console.log(info)
							}
						})

					}
				})
			},
			//
			beforeConfirm() {
				this.$util.debounce(this.sub_sure, 1000, true);
			},
			/**
			 * @func 提交表单
			 */
			sub_sure() {
				if (this.isagain) {
					return this.$message.info('请勿重复点击');
				}

				// 表单验证
				if (this.name.trim() == '') {
					this.$message.info(this.i18n['请输入收货人姓名']);
					this.name = '';
					return false;
				};
				if (!/^1(3|4|5|6|7|8|9)\d{9}$/.test(this.phone)) {
					let text = !this.phone ? this.i18n['请输入手机号'] : this.i18n['手机号格式不正确'];
					this.$message.info(text);
					return false;
				}
				if (this.address.trim() == '') {
					this.$message.info(this.i18n['地区不能为空']);
					return false;
				}
				//判断是否含有特殊字符
				let iconRule1 = /[`~!@#$%^&*_\+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&* ——\+={}|《》？：“”【】；‘’，。]/im;

				// 判断是否含有emoji表情
				let iconRule2 =
					/[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF][\u200D|\uFE0F]|[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF]|[0-9|*|#]\uFE0F\u20E3|[0-9|#]\u20E3|[\u203C-\u3299]\uFE0F\u200D|[\u203C-\u3299]\uFE0F|[\u2122-\u2B55]|\u303D|[\A9|\AE]\u3030|\uA9|\uAE|\u3030/ig;
				if (this.addressDesc.trim() == '') {
					this.$message.info(this.i18n['详细地址不能为空']);
					this.addressDesc = '';
					return false;
				}
				//if (iconRule1.test(this.addressDesc)) {
					//this.$message.info(this.i18n['详细地址不能含有特殊字符']);
					// this.addressDesc = '';
				//	return false;
			//	}
				if (iconRule2.test(this.addressDesc)) {
					this.$message.info(this.i18n['详细地址不能含有表情']);
					// this.addressDesc = '';
					return false;
				}
				// 将状态改变
				this.isagain = true


				let data = {
					name: this.name, // 收货人姓名
					mobile: this.phone, // 收货人手机
					is_default: this.is_default ? '1' : '0', // 是否默认地址
					address: this.addressDesc, // 详细地址
					province: this.province, // 省
					city: this.city, // 市
					district: this.district, // 区
					provinceCode: this.provinceCode, // 省 code码
					cityCode: this.cityCode, //市 code码
					districtCode: this.districtCode, //区 code码
					sex: this.sex,
					label_name: this.default_serve ? this.default_serve.name : '' // 标签name
				}
				// 判断提交的接口
				let url = global.apiUrls.postUserAddressAddAddress;
				if (this.edit_id) {
					data.address_id = this.edit_id
					url = global.apiUrls.postUserAddressEditAddress;
				}
				console.log('提交的地址参数', data);
				// 提交请求
				this.$api.post(url, data)
					.then(res => {
						console.log(res, '添加/编辑成功');
						if (res.statusCode == 200 && res.data.code == 1) {
							this.$message.info(this.i18n['保存成功']);
							// 通知商品详情页更新地址数据
							uni.$emit('refreshAddress', res.data.data.address_id);
							setTimeout(() => {
								uni.navigateBack()
							}, 800);
						} else {
							this.isagain = false
							this.$message.info(res.data.msg)
						}

					})
					.catch(err => {
						this.isagain = false
						console.log("err: ", err);
					})
			},
			/**
			 * @func 清除手机号
			 */
			clear() {
				this.phone = '';
			}
		}
	}
</script>
<style lang="scss" scoped>
	.page {
		min-height: 100vh;
		background: #FFFFFF;
	}

	.tag {
		padding: 0 16rpx;
		margin-right: 10rpx;
		line-height: 52rpx;
		border: 1rpx solid #333;
	}

	.bottom-status {
		height: 156rpx;
		height: calc(156rpx + constant(safe-area-inset-bottom));
		height: calc(156rpx + env(safe-area-inset-bottom));
	}

	.text-area {
		height: 160rpx !important;
		background-color: #F6F6F6;
		padding: 20rpx;
		border-radius: 8rpx;
	}

	/deep/ .uni-textarea-textarea {
		line-height: 1.5;
	}

	.addAddr {
		padding: 0 20upx;

		.uni-list-cell {
			display: flex;
			flex-direction: row;
			justify-content: space-between;
			align-items: center;
			margin: 20upx 0;
			box-sizing: border-box;
			height: 100upx;
			font-size: 30upx;
			background: #fff;
		}

		.addr {
			font-size: 32upx;
			padding: 30upx 0;
			border-bottom: 1px solid #f5f5f7;
			width: 100%;
			display: flex;
			flex-direction: row;
			align-items: center;

			.addr_title {
				display: inline-block;
				width: 180rpx;
			}

			.chose_addr {
				display: flex;
				flex-direction: row;
				align-items: center;
				justify-content: space-between;
				width: 70%;
			}
		}

		.cell {
			font-size: 32upx;
			display: flex;
			flex-direction: row;
			align-items: center;
			padding: 32rpx 0;
			border-bottom: 1px solid #f5f5f7;

			.title {
				display: inline-block;
				width: 180rpx;
			}

			input {
				flex: 1;
				color: #333;
			}

			.text-area {
				flex: 1;
			}
		}

		.address {
			display: flex;
			flex-direction: column;
			font-size: 32upx;

			.title {
				line-height: 110upx;
			}
		}

		.tips {
			padding: 20upx 0;
			font-size: 26upx;
		}
	}

	.placeholderClass {
		font-size: 32rpx;
		color: #BFBFBF;
	}

	.active {
		color: $theme;
	}

	switch::before,
	switch::after {
		content: "";
	}

	.bottom-action {
		position: fixed;
		right: 32rpx;
		left: 32rpx;
		bottom: 56rpx;
		bottom: calc(56rpx + constant(safe-area-inset-bottom));
		bottom: calc(56rpx + env(safe-area-inset-bottom));
		display: flex;

		view {
			height: 88rpx;
			flex: 1;
			line-height: 88rpx;
			text-align: center;
			border-radius: 88rpx;
			color: #FFFFFF;
		}

		.btn2 {
			background: $bgtheme;
		}
	}


	/deep/ .switch {
		transform: scale(0.7);
	}

	.serve-mask {
		background: rgba(0, 0, 0, 0.3);
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		z-index: 9999;
	}

	.serve-pop {
		height: 100rpx;
		position: fixed;
		bottom: 0;
		width: 100%;
		background: #FFFFFF;
		z-index: 11111;

		input {
			margin-left: 32rpx;
			width: 528rpx;
			height: 66rpx;
			background: #F6F7F9;
			opacity: 1;
			border-radius: 35rpx;
			font-size: 28rpx;
			font-weight: 400;
			color: #99999A;
			text-indent: 1em;
		}

		button {
			width: 140rpx;
			height: 66rpx;
			background: #FF9D00;
			border-radius: 33rpx;
			font-size: 28rpx;
			font-weight: 400;
			color: #FFFFFF;
		}
	}

	.left-0 {
		margin-left: 2rpx;
	}

	.radius-left {
		border-top-left-radius: 20rpx;
		border-bottom-left-radius: 20rpx;
	}

	.radius-right {
		border-top-right-radius: 20rpx;
		border-bottom-right-radius: 20rpx;
	}

	.bg-orange2 {
		background: #FF9D00;
		color: #fff;
	}

	.placeholder {
		font-size: 28rpx;
		font-weight: 400;
		color: #BFBFBF;
	}

	.placeholderServe {
		font-size: 28rpx;
		font-weight: 400;
		color: #99999A;
	}

	/deep/ .uni-popup__wrapper.uni-custom .uni-popup__wrapper-box {
		border: none;
		padding: 0;
	}
</style>
